<template>
  <div class="main-box">
    <div class="table-box">
      <ProTable ref="proTableRef" :columns="columns" :request-api="roleApi.page" :data-callback="dataCallback">
        <template #tableHeader>
          <el-button size="default" type="success" class="ml10" @click="onOpenAddRole('add')" v-auth="'system:role:add'">
            <el-icon>
              <CirclePlus />
            </el-icon>
            {{ $t("message.roleBtn.addRole") }}
          </el-button>
        </template>
        <template #operation="scope">
          <el-button size="small" text type="primary" @click="onOpenEditRole('edit', scope.row)" v-auth="'system:role:update'">
            <el-icon><Edit /></el-icon>
            {{ $t("message.commonBtn.edit") }}
          </el-button>
          <el-button
            :disabled="scope.row.systemMark === 'SYSTEM'"
            size="small"
            text
            type="primary"
            @click="onRowDel(scope.row)"
            v-auth="'system:role:delete'"
          >
            <el-icon><Delete /></el-icon>
            {{ $t("message.commonBtn.delete") }}
          </el-button>
          <el-dropdown>
            <span class="el-dropdown-link">
              <el-button text size="small" type="primary">
                <el-icon><ArrowDownBold /></el-icon>
                {{ $t("message.roleBtn.grant") }}
              </el-button>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  :disabled="scope.row.code == 'SuperAdmin' || !auth('system:role:grantRoleMenus')"
                  @click="openGrantMenu(scope.row)"
                >
                  {{ $t("message.roleBtn.grantMenu") }}
                </el-dropdown-item>
                <el-dropdown-item
                  divided
                  :disabled="scope.row.code == 'SuperAdmin' || !auth('system:role:grantRoleResource')"
                  @click="openGrantResource(scope.row)"
                >
                  {{ $t("message.roleBtn.grantApi") }}
                </el-dropdown-item>
                <el-dropdown-item
                  divided
                  :disabled="scope.row.code == 'SysCommon' || !auth('system:role:grantRoleUser')"
                  @click="openGrantUser(scope.row)"
                >
                  {{ $t("message.roleBtn.grantUser") }}
                </el-dropdown-item>
                <el-dropdown-item
                  divided
                  :disabled="scope.row.code == 'SysCommon' || !auth('system:role:grantRoleUser')"
                  @click="openGrantOrg(scope.row)"
                >
                  {{ $t("message.roleBtn.grantOrg") }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </ProTable>
    </div>
    <RoleDialog ref="roleDialogRef" @refresh="getTableData()" :dict-data="state.dictData" />
    <GrantUser ref="grantUserRef" />
    <GrantOrg ref="grantOrgRef" />
    <GrantMenu ref="grantMenuRef" />
    <GrantApiResource ref="grantApiResourceRef" :data-scope="state.dictData" />
  </div>
</template>

<script setup lang="tsx" name="systemRole">
import { defineAsyncComponent, reactive, ref, watchEffect } from "vue";
import { ElMessageBox } from "element-plus";
import { feature } from "@/utils/axios-utils";
import { DictData, SysRole } from "@/api-services/models/system";
import roleApi from "@/api-services/apis/system/roleApi";
import dictDataApi from "@/api-services/apis/system/dictDataApi";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import ProTable from "@/components/ProTable/index.vue";
import { SqlSugarPagedList, UnifyResult } from "@/api-services/unifyResult";
import { auth } from "@/utils/authFunction";
import { ArrowDownBold, CirclePlus, Delete, Edit } from "@element-plus/icons-vue";
import { useI18n } from "vue-i18n";
import { NotificationError, NotificationSuccess } from "@/utils/notification";
const { t } = useI18n();
// 引入组件
const RoleDialog = defineAsyncComponent(() => import("./component/editRole.vue"));
const GrantUser = defineAsyncComponent(() => import("./component/grantUser.vue"));
const GrantOrg = defineAsyncComponent(() => import("./component/grantOrg.vue"));
const GrantMenu = defineAsyncComponent(() => import("./component/grantMenu.vue"));
const GrantApiResource = defineAsyncComponent(() => import("./component/grantApiResource.vue"));
// 定义变量内容
const proTableRef = ref<ProTableInstance>();
const roleDialogRef = ref<InstanceType<typeof RoleDialog> | null>(null);
const grantUserRef = ref<InstanceType<typeof GrantUser> | null>(null);
const grantOrgRef = ref<InstanceType<typeof GrantOrg> | null>(null);
const grantMenuRef = ref<InstanceType<typeof GrantMenu> | null>(null);
const grantApiResourceRef = ref<InstanceType<typeof GrantApiResource> | null>(null);
const state = reactive({
  loading: false,
  roleData: [] as Array<SysRole.SysRoleInfo>, // 机构列表数据
  dictData: [] as Array<DictData.SysDictData>, //字典数据
  editOrgTitle: ""
});
const getRoleDataScope = async () => {
  let res = await dictDataApi.getDatalistByType("RoleDataScope");
  state.dictData = res.data.data ?? [];
};

const dataCallback = (queryRes: UnifyResult<SqlSugarPagedList<SysRole.SysRoleInfo>>) => {
  let data = queryRes.data;
  return {
    items: data.items,
    totalCount: data.totalCount,
    pageIndex: data.pageIndex,
    pageSize: data.pageSize
  };
};
const columns: ColumnProps<SysRole.SysRoleInfo>[] = [
  {
    prop: "roleName",
    label: t("message.roleInfo.roleName"),
    search: { el: "input", key: "roleName" }
  },
  { prop: "code", label: t("message.roleInfo.code") },
  {
    prop: "dataScope",
    label: t("message.roleInfo.dataScope"),
    render: scope => {
      let data = state.dictData.filter(item => item.value == scope.row.dataScope)[0];
      return (
        <el-tag size={data?.tagSize} type={data?.tagType}>
          {data?.name}
        </el-tag>
      );
    }
  },
  { prop: "sort", label: t("message.roleInfo.sort") },
  { prop: "operation", label: t("message.commonBtn.oper"), fixed: "right" }
];

// 初始化表格数据
const getTableData = async () => {
  proTableRef.value?.getTableList();
};
// 打开新增角色弹窗
const onOpenAddRole = (type: string) => {
  roleDialogRef.value?.openDialog(type, {});
};
// 打开修改角色弹窗
const onOpenEditRole = (type: string, row: SysRole.SysRoleInfo) => {
  roleDialogRef.value?.openDialog(type, row);
};
// 删除角色
const onRowDel = (row: SysRole.SysRoleInfo) => {
  ElMessageBox.confirm(`${t("message.roleAlter.isDeleteRole")}：“${row.roleName}”`, t("message.commonBtn.alter"), {
    confirmButtonText: t("message.userAlter.confirm"),
    cancelButtonText: t("message.userAlter.cancel"),
    type: "warning"
  })
    .then(async () => {
      const [err] = await feature(roleApi.delete([{ id: row.id }]));
      if (err) {
        NotificationError(err.message);
      } else {
        NotificationSuccess(t("message.roleAlter.deleteRoleSuccess"));
        getTableData();
      }
    })
    .catch();
};

watchEffect(() => {
  getRoleDataScope();
});

const openGrantUser = (role: SysRole.SysRoleInfo) => {
  grantUserRef.value?.openDialog(role.id!);
};
const openGrantMenu = (role: SysRole.SysRoleInfo) => {
  grantMenuRef.value?.openGrantMenu(role.id!);
};
const openGrantResource = (role: SysRole.SysRoleInfo) => {
  grantApiResourceRef.value?.openGrantResource(role);
};
const openGrantOrg = (role: SysRole.SysRoleInfo) => {
  const param = {
    //requestApi: userCenterApi.orgTree,
    roleInfo: role
  };
  grantOrgRef.value?.orgSelector(param);
};
</script>
